package com.zhaoyd.uaademo.config.security.handler;

import com.zhaoyd.uaademo.core.BaseLogger;
import com.zhaoyd.uaademo.core.ResultData;
import com.zhaoyd.uaademo.util.JsonBeanConvertUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class MyAccessDeniedHandler extends BaseLogger implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        log.warn("access denied:"+accessDeniedException.getMessage());
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(HttpStatus.FORBIDDEN.value());
        PrintWriter writer = response.getWriter();
        ResultData resultData = ResultData.fail("访问受限:"+accessDeniedException.getMessage());
        writer.write(JsonBeanConvertUtils.beanToJson(resultData));
        writer.flush();
        writer.close();
    }
}
